package com.atguigu.lease.web.app.controller.login;



import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.atguigu.lease.common.Redis.RedisConstant;
import com.atguigu.lease.common.context.LoginSysUser;
import com.atguigu.lease.common.context.LoginSysUserContext;
import com.atguigu.lease.common.exception.define.BusException;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@Tag(name = "登录管理")
@RequestMapping("/app/")
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private Client client;
    @GetMapping("login/getCode")
    @Operation(summary = "获取短信验证码")
    public Result getCode(@RequestParam String phone) {
        System.out.println(phone);
        if (!StringUtils.hasText(phone)){
            throw new BusException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY.getCode(),ResultCodeEnum.APP_LOGIN_PHONE_EMPTY.getMessage());
        }
        Long expire = redisTemplate.getExpire(RedisConstant.APP_LOGIN_PREFIX + phone);
        if(RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
            throw new BusException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN.getCode(),ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN.getMessage());
        }
        String code = this.randomCode();
        System.out.println(code);
        this.sendCode(phone,code);
        redisTemplate.opsForValue().set(RedisConstant.APP_LOGIN_PREFIX+phone,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
        System.out.println("send mes");
        return Result.ok();
    }

    @PostMapping("login")
    @Operation(summary = "登录")
    public Result<String> login(@RequestBody LoginVo loginVo) {
        String code = loginVo.getCode();
        String phone = loginVo.getPhone();
        if (!StringUtils.hasText(code)){
            throw new BusException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY.getCode(),ResultCodeEnum.APP_LOGIN_CODE_EMPTY.getMessage());
        }
        if (!StringUtils.hasText(phone)){
            throw new BusException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY.getCode(),ResultCodeEnum.APP_LOGIN_PHONE_EMPTY.getMessage());
        }
        String captchaCode = redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + phone);
        if (captchaCode == null){
            throw new BusException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED.getCode(),ResultCodeEnum.APP_LOGIN_CODE_EXPIRED.getMessage());
        }
        UserInfo user = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
        if(user == null){
            user = new UserInfo();
            user.setPhone(loginVo.getPhone());
            user.setNickname("用户-"+loginVo.getPhone().substring(7));
            user.setStatus(BaseStatus.ENABLE);
            userInfoService.save(user);
        }
        if (user.getStatus() == BaseStatus.DISABLE){
            throw new BusException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR.getCode(),ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR.getMessage());
        }
        String token = JwtUtil.createToken(user.getId(), user.getNickname());
        return Result.ok(token);
    }

    @GetMapping("info")
    @Operation(summary = "获取登录用户信息")
    public Result<UserInfoVo> info() {
        LoginSysUser contex = LoginSysUserContext.getContex();

        UserInfo user = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId, contex.getUserid()));
        if(user==null){
            throw new BusException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR.getCode(),ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR.getMessage());
        }
        if(user.getStatus().equals(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR)){
            throw new BusException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR.getCode(),ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR.getMessage());
        }
        UserInfoVo userInfoVo = new UserInfoVo(user.getNickname(),user.getAvatarUrl());

        return Result.ok(userInfoVo);
    }
    public String randomCode(){
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<6;i++){
            int it = random.nextInt(10);
            sb.append(it);
        }
        return sb.toString();
    }


    public void sendCode(String phone, String code){
//        专门负责发 给哪发和发什么你需要传
//     第一步：对接阿里云短信服务
//     第二步：通过阿里云的api代码进行改造
//        1、创建一个Client对象放入ioc
//        2、在发短信的位置拿到Client对象进行发短信

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":"+ "\"" + code + "\"" + "}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (Exception error) {
            throw new BusException(ResultCodeEnum.SERVICE_ERROR.getCode(),error.getMessage());
        }

    }




}
